package com.lession.config;

import com.lession.service.PxtcsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

@Component
public class AuthRepository {
	
	//存储token的map结构:{ygbh:token值}
	private Map<String, String> userRepo = new Hashtable<>();
	//存储token存活时间的map结构:{token值:时间戳}
	private Map<String, Long> repository = new Hashtable<>();
	// key:value = userId : token
	private Map<String, String> tokenRepo = new Hashtable<>();
	@Autowired
	private PxtcsService pxtcsService;
	
	/**
	 * 权限保存与覆盖
	 */
	public String save(String key) {
		// 二重登录判定 && 默认可以同时登录
		String multi_login = pxtcsService.getValByKey("multi_login");
		if (userRepo.containsKey(key) && (!"1".equals(multi_login) || StringUtils.isEmpty(multi_login))) {
			String oldTat = userRepo.get(key);
			this.clear(oldTat);
		}
		String tokenStr;
		while (true) {
			tokenStr = RandomStringUtils.randomAlphanumeric(50);
			if (!userRepo.containsKey(tokenStr)) {
				userRepo.put(key, tokenStr);
				repository.put(tokenStr, new Date().getTime());
				break;
			}
		}
		return tokenStr;
	}
	
	/**
	 * 权限清空
	 */
	public void clear(String tokenStr) {
		repository.remove(tokenStr);
		for (String key : userRepo.keySet()) {
			if (userRepo.get(key).equals(tokenStr)) {
				userRepo.remove(key);
				tokenRepo.remove(key);
				break;
			}
		}
	}
	
	public String getKey(String tokenStr) {
		for (String key : userRepo.keySet()) {
			if (userRepo.get(key).equals(tokenStr)) {
				return key;
			}
		}
		return "";
	}
	
	public String getTokenStr(String userId) {
		String tokenStr = userRepo.get(userId);
		if (isPermitted(tokenStr)) {
			return tokenStr;
		}
		return null;
	}
	
	/**
	 * 是否有权限
	 */
	public boolean isPermitted(String tokenStr) {
		if (StringUtils.isEmpty(tokenStr)) {
			return false;
		}
		if (!repository.containsKey(tokenStr)) {
			return false;
		}
		long value = repository.get(tokenStr);
		long now = new Date().getTime();
		if (now - value >= 1000 * 60 * 60 * 4) {
			// 连续4个小时不动，清空仓库
			clear(tokenStr);
			return false;
		}
		repository.put(tokenStr, now);
		return true;
	}
	
}
